//
//  LXCustomerApplyViewController.m
//  EnterpriseEdition
//
//  Created by ypj on 2021/10/14.
//

#import "LXCustomerApplyViewController.h"
#import "LXTableViewCell.h"
#import "LXApplyAnnexTableCell.h"
#import "LXRemarkTabelViewCell.h"
#import "LXChooseManagerViewController.h"
#import "FuZeRenModel.h"
#import "KeHuInfoModel.h"
#import "LXChooseSexTableViewCell.h"


@interface LXCustomerApplyViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong)  UITableView   *tableView;
@property (nonatomic, strong) NSMutableArray *data;
@property (nonatomic) NSMutableArray *annexAry; //  维修图片  展示用
@property (nonatomic) NSMutableArray *annexDataAry; //  维修图片 提交用
@property (nonatomic) NSMutableDictionary *loanDic;


// 负责车管id
@property (nonatomic, strong) NSString *chargeManagerId;
// 负责销售id
@property (nonatomic, strong) NSString *chargeSaleId;
// 负责销售id
@property (nonatomic, assign) NSInteger sex;


@end

@implementation LXCustomerApplyViewController
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = White_Color;
    
  
    
    [self.view addSubview:self.tableView];
    
    UIButton *createButton = [UIButton buttonWithType:UIButtonTypeCustom];
    createButton.frame = CGRectMake(15, kScreenHeight - 60, ScreenWidth-30, kComHeight);
    
    createButton.backgroundColor = mainColor;
    [createButton setTitleColor:White_Color forState:UIControlStateNormal];
    [createButton createBordersWithColor:nil withCornerRadius:4.0 andWidth:0];
    [createButton addTarget:self action:@selector(createButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:createButton];
    
    if (self.type == 1) {
        [self layoutCustomNav:self.view title:@"新增客户"];
        [createButton setTitle:@"确认新增" forState:UIControlStateNormal];
    }
    else {
        [self layoutCustomNav:self.view title:@"修改客户"];
        [createButton setTitle:@"确认修改" forState:UIControlStateNormal];
    }
     
    self.sex = 1;
    
    
    NSDictionary *dic = @{
        @"url":@"upLoad_B",
    };
    self.annexAry = [NSMutableArray array];
    self.annexDataAry = [NSMutableArray array];
    [self.annexAry addObject:dic];
    self.loanDic = [NSMutableDictionary dictionary];
    self.data = [NSMutableArray array];
    
    [self loadData];
    
    
}

-(void)loadData{
    
    
    if (self.type == 2) {
        [self.loanDic setValue:self.kehuModel.customerName forKey:@"customerName"];
        [self.loanDic setValue:self.kehuModel.idNum forKey:@"idNum"];
        [self.loanDic setValue:self.kehuModel.address forKey:@"address"];
        [self.loanDic setValue:self.kehuModel.customerPhone forKey:@"customerPhone"];
        [self.loanDic setValue:self.kehuModel.emergencyContact forKey:@"emergencyContact"];
        [self.loanDic setValue:self.kehuModel.emergencyPhone forKey:@"emergencyPhone"];
        [self.loanDic setValue:self.kehuModel.chargeSale forKey:@"chargeSale"];
        self.chargeSaleId = self.kehuModel.chargeSaleId;
        [self.loanDic setValue:self.kehuModel.chargeManager forKey:@"chargeManager"];
        self.chargeManagerId = self.kehuModel.chargeManagerId;
        
        self.sex = self.kehuModel.sex;
    
        [self.loanDic setValue:self.kehuModel.remarks forKey:@"remarks"];

        
        //图片
        for (NSString *url in self.kehuModel.pics) {
            NSString *imageUrl = [NSString stringWithFormat:@"%@%@",HTTP_URL,url];
            [self.annexAry insertObject:@{@"url":imageUrl} atIndex:0];
            [self.annexDataAry insertObject:url atIndex:0];
        }

    }
    
    
    NSArray *ary0 = @[
        @{
            @"title":@"*姓名",
            @"key":@"customerName",
            @"placeHolder" : @"请输入客户姓名",
            @"canEdit":@(YES),
            @"inputType":@(CHINESE),
            @"maxLength":@(11),
            @"height":@(kComHeight)
        },
        @{
            @"title":@"身份证号",
            @"key":@"idNum",
            @"placeHolder" : @"请输入客户身份证号",
            @"canEdit":@(YES),
            @"showAccess":@(NO),
            @"inputType":@(NUM_LATTER),
            @"maxLength":@(18),
            @"height":@(kComHeight)
        },
        @{
            @"title":@"家庭住址",
            @"key":@"address",
            @"placeHolder" : @"请输入家庭住址",
            @"canEdit":@(YES),
            @"showAccess":@(NO),
            @"inputType":@(CHINESE),
            @"maxLength":@(18),
            @"height":@(kComHeight)
        },
        @{
            @"title":self.type==1?@"*手机号":@"手机号",
            @"key":@"customerPhone",
            @"placeHolder" : @"请输入手机号",
            @"canEdit":self.type==1?@(YES):@(NO),
            @"showAccess":@(NO),
            @"inputType":@(NUM),
            @"keyboardType":@(UIKeyboardTypeNumberPad),
            @"maxLength":@(11),
            @"height":@(kComHeight)
        },
        @{
            @"title":@"性别",
            @"key":@"sex",
            @"height":@(kComHeight)
        }
    ];
    [self.data addObject:ary0];
    NSArray *ary1 = @[
        @{
            @"title":@"紧急联系人",
            @"key":@"emergencyContact",
            @"placeHolder" : @"请输入紧急联系人姓名",
            @"canEdit":@(YES),
            @"showAccess":@(NO),
            @"inputType":@(CHINESE),
            @"maxLength":@(11),
            @"height":@(kComHeight)
        },
        @{
            @"title":@"紧急联系人号码",
            @"key":@"emergencyPhone",
            @"placeHolder" : @"请输入紧急联系人号码",
            @"canEdit":@(YES),
            @"showAccess":@(NO),
            @"keyboardType":@(UIKeyboardTypeNumberPad),
            @"inputType":@(NUM),
            @"maxLength":@(11),
            @"height":@(kComHeight)
        },
        @{
            @"title":@"负责销售",
            @"key":@"chargeSale",
            @"placeHolder" : @"请选择销售",
            @"canEdit":@(NO),
            @"showAccess":@(YES),
            @"sel":@"clickSaleAction",
            @"height":@(kComHeight)
        },
        @{
            @"title":@"负责车管",
            @"key":@"chargeManager",
            @"placeHolder" : @"请选择车管",
            @"canEdit":@(NO),
            @"showAccess":@(YES),
            @"sel":@"clickCarManageAction",
            @"height":@(kComHeight)
        },
    ];
    [self.data addObject:ary1];
    
    NSArray *ary2 = @[
        @{
            @"title":@"备注",
            @"key":@"remarks",
            @"height":@(150)
        },
        @{
            @"title":@"附加图片(最多5张)",
            @"key":@"annex",
            @"height":@(kComAnnexHeight)
        },
    ];
    [self.data addObject:ary2];
    
    
   
    [self.tableView reloadData];
 
}




-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
     return self.data.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  [self.data[section] count];
}



-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *dic = self.data[indexPath.section][indexPath.row];

    // 维修图片
    if ([dic[@"key"] isEqualToString:@"annex"]) {
        LXApplyAnnexTableCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LXApplyAnnexTableCell class])];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setClipsToBounds:YES];
        cell.titleLab.text = dic[@"title"];
        [cell reloadAnnexData:self.annexAry WithMaxNum:5];
        
        // 添加图片
        [cell setCallBackTakeAnnex:^(NSInteger num) {
            
            [[LXPhotoHelper shareHelper] showImageViewSelcteWithResultBlock:^(id data) {
                
                [self uploadImage:data];
                
            } andMultipleImageBlock:^(id data) {
                
                [self uploadImage:data];
                
            } andSelectedNum:5 - self.annexDataAry.count];
            
        }];
        
        
        // 放大图片
        [cell setCallBackExtendAnnex:^(NSInteger num,id obj) {
            LXBigImageView *view = [[LXBigImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) WithShowImageAry:self.annexDataAry];
            [view.scrollView setContentOffset:CGPointMake(ScreenWidth*num, 0) animated:NO];
            [[UIApplication sharedApplication].delegate.window addSubview:view];
            
        }];
        // 删除图片
        [cell setCallBackDeleteAnnex:^(NSInteger num) {
            
            [self.annexAry removeObjectAtIndex:num];
            [self.annexDataAry removeObjectAtIndex:num];

            [self.tableView reloadData];
        }];
        
        
        return cell;
    }
    // 备注
   else if([dic[@"key"]  isEqualToString:@"remarks"]){
       LXRemarkTabelViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LXRemarkTabelViewCell class])];
       cell.selectionStyle = UITableViewCellSelectionStyleNone;
       [cell setClipsToBounds:YES];
       cell.textView.placeholder = @"请输入 ~";
       cell.textView.maxLength = 200;
       
       cell.remarkTitle.text = dic[@"title"];
       cell.textView.text = self.loanDic[dic[@"key"]];
       [cell setTextViewEdit:^(NSString * _Nonnull textStr) {
           self.loanDic[dic[@"key"]]  = textStr;
       }];
       return cell;
   }
   else if([dic[@"key"] isEqualToString:@"sex"]){
       
       LXChooseSexTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LXChooseSexTableViewCell class])];
       cell.selectionStyle = UITableViewCellSelectionStyleNone;
       [cell setClipsToBounds:YES];
       
       
       if (self.sex == 1) {
           cell.boyBtn.selected = YES;
           cell.grilBtn.selected = NO;
       }
       else if(self.sex == 2){
           cell.boyBtn.selected = NO;
           cell.grilBtn.selected = YES;
       }
       
       [cell.boyBtn whenTapped:^{
           self.sex = 1;
           cell.boyBtn.selected = YES;
           cell.grilBtn.selected = NO;
           
       }];
       [cell.grilBtn whenTapped:^{
           self.sex = 2;
           cell.boyBtn.selected = NO;
           cell.grilBtn.selected = YES;
       }];
       
       
       
       return cell;
       
   }
    LXTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LXTableViewCell class])];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell setClipsToBounds:YES];
    

    cell.cellDic = dic;
    cell.textFiled.hidden = NO;
    cell.subTitleLab.hidden = YES;
    cell.textFiled.text = self.loanDic[dic[@"key"]];
    

    cell.textfiledChangeBlock = ^(NSString * _Nonnull textStr) {
        self.loanDic[dic[@"key"]]  = textStr;
    };
    
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *dic = self.data[indexPath.section][indexPath.row];
    if ([dic[@"key"] isEqualToString:@"annex"]) {
        return [LXApplyAnnexTableCell getCellHeightWithDataSource:self.annexAry] + 30;
    }
    
    return [dic[@"height"] doubleValue];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
   
    NSDictionary *dic = self.data[indexPath.section][indexPath.row];
    NSString * selName = dic[@"sel"];
    SEL action = NSSelectorFromString(selName);
    if ([self respondsToSelector:action]) {
        [self performSelector:action withObject:nil afterDelay:0];
    }
    
    
}

-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 0)];
    footerView.backgroundColor = [UIColor colorWithHexString:@"#F7F8FA"];
    return footerView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10;
}


// MARK: 选择负责销售
-(void)clickSaleAction{
    [self.view endEditing:YES];
    
    LXChooseManagerViewController *vc = [[LXChooseManagerViewController alloc] init];
    WEAKSELF
    [vc setToSendValue:^(FuZeRenModel * _Nonnull model) {
        [weakSelf.loanDic setValue:model.realName forKey:@"chargeSale"];
        weakSelf.chargeSaleId = model.ID;
        [weakSelf.tableView reloadData];
    }];
    [self pushToNextController:vc];
}
// MARK: 选择负责车管
-(void)clickCarManageAction{
    [self.view endEditing:YES];
    
    LXChooseManagerViewController *vc = [[LXChooseManagerViewController alloc] init];
    WEAKSELF
    [vc setToSendValue:^(FuZeRenModel * _Nonnull model) {
        [weakSelf.loanDic setValue:model.realName forKey:@"chargeManager"];
        weakSelf.chargeManagerId = model.ID;
        [weakSelf.tableView reloadData];
    }];
    [self pushToNextController:vc];
}

-(void)commitInfo{
    [self.view endEditing:YES];
    if (StringIsEmpty(self.loanDic[@"customerName"])) {
        showAlert(@"请输入客户姓名");
        return;
    }
    if (![NSString isChinese:self.loanDic[@"customerName"]]) {
        showAlert(@"客户姓名不正确");
        return;
    }
    if (StringIsEmpty(self.loanDic[@"customerPhone"])){
        showAlert(@"手机号格式不正确");
        return;
    }
    if (![self.loanDic[@"customerPhone"] isValidPhone]){
        showAlert(@"手机号格式不正确");
        return;
    }
    
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    // 客户姓名
    [params setValue:self.loanDic[@"customerName"] forKey:@"customerName"];
    // 身份证号
    [params setValue:self.loanDic[@"idNum"] forKey:@"idNum"];
    // 家庭住址
    [params setValue:self.loanDic[@"address"] forKey:@"address"];
    // 手机号
    [params setValue:self.loanDic[@"customerPhone"] forKey:@"customerPhone"];
    // 性别
    [params setValue:@(self.sex) forKey:@"sex"];
    // 紧急联系人
    [params setValue:self.loanDic[@"emergencyContact"] forKey:@"emergencyContact"];
    // 紧急联系电话
    [params setValue:self.loanDic[@"emergencyPhone"] forKey:@"emergencyPhone"];
    // 销售
    [params setValue:self.loanDic[@"chargeManager"] forKey:@"chargeManager"];
    [params setValue:self.chargeSaleId forKey:@"chargeSaleId"];
    // 车管
    [params setValue:self.loanDic[@"chargeSale"] forKey:@"chargeSale"];
    [params setValue:self.chargeManagerId forKey:@"chargeManagerId"];
    // 附件
    NSString *customImage = [NSString toJSONData:self.annexDataAry];
    [params setValue:customImage forKey:@"customImage"];
    // 备注
    [params setValue:self.loanDic[@"remarks"] forKey:@"remarks"];

    NSString *url;
    if (self.type == 1) {
        url = POST_AddKeHu_URL;
    }
    else {
        url = POST_UpdateKeHu_URL;
        [params setValue:self.kehuModel.ID forKey:@"id"];
    }
    
    
    [MSNetworkManager postRevertUrl:url params:params success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
        if (isSuccess) {
            
            kUserDefaultSetBool(YES, kRefreshStr);
            
            if (self.type == 1) {
                
                showAlert(@"新增成功");
            }
            else {
                showAlert(@"修改成功");
            }
            
            [self.navigationController popViewControllerAnimated:YES];
        }
    } failure:^(NSUInteger code, NSString * _Nonnull message) {
    } withShowHud:YES];
    

}

-(void)createButtonClick{
    [self commitInfo];
}
-(void)uploadImage:(NSArray *)ary{
    
    [self.annexAry removeLastObject];
    
    MBProgressHUD *hud = [MBProgressHUD showGif];
        
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        
    dispatch_async(queue, ^{
    
    [ary enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    
        [MSNetworkManager postRevertUrl:POST_UploadFile_URL params:@{@"type":@"1"} formData:@[obj] success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
            if (isSuccess) {
                
                NSString *imageUrl = [NSString stringWithFormat:@"%@%@",HTTP_URL,resonseObj[@"url"]];

                [self.annexAry addObject:@{
                    @"url":imageUrl
                }];
                [self.annexDataAry addObject:resonseObj[@"url"]];
                
                if (idx == ary.count-1) {
                    [hud hide];
                    [self.annexAry addObject:@{
                        @"url":@"upLoad_B",
                    }];
                    [self.tableView reloadData];
                }
                dispatch_semaphore_signal(semaphore);
            }
        } failure:^(NSUInteger code, NSString * _Nonnull message) {
            dispatch_semaphore_signal(semaphore);
            [hud hide];
        } withShowHud:NO];
        
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        
        
     }];
    });

}
- (UITableView *)tableView{
    
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kViewTopHeight, ScreenWidth, kScreenHeight - kViewTopHeight - 60) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor colorWithHexString:@"#F7F8FA"];
        [_tableView registerClass:[LXTableViewCell class] forCellReuseIdentifier:NSStringFromClass([LXTableViewCell class])];
        [_tableView registerClass:[LXApplyAnnexTableCell class] forCellReuseIdentifier:NSStringFromClass([LXApplyAnnexTableCell class])];
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([LXRemarkTabelViewCell class]) bundle:nil]  forCellReuseIdentifier:NSStringFromClass([LXRemarkTabelViewCell class])];
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([LXChooseSexTableViewCell class]) bundle:nil]  forCellReuseIdentifier:NSStringFromClass([LXChooseSexTableViewCell class])];

        
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0;
        }
        
    }
    return _tableView;
}
@end
